<template>
  <div>
    <Content title="用户" subTitle="分配角色" path="/user">
      <div slot="body">
        <div style="padding-left: 20px;text-align: center" v-loading="loading">
          <el-transfer v-model="choosed" :data="data" style="text-align: left; display: inline-block"
                       :titles="['未选角色', '已选角色']"
                       :button-texts="['移除角色', '添加角色']">
          </el-transfer>
        </div>
      </div>
    </Content>
    <div style="padding: 15px">
      <router-link to="/user">
        <el-button plain round type="info" icon="el-icon-back">返回</el-button>
      </router-link>
      <el-button plain type="primary" @click="save" icon="el-icon-circle-check">保存</el-button>
    </div>
  </div>
</template>

<script>
  import Content from '../../components/Content.vue'
  import {Role} from '../../utils/resource'
  import {showSaveResponse} from '../../utils/element-helper'

  export default {
    name: 'userRole',
    components: {
      Content,
    },
    data() {
      return {
        loading: false,
        data: [],
        choosed: []
      }
    },
    created() {
      this.loading = true
      Promise.all([this.loadRoles(), this.loadUserRoles()]).then((res) => {
        this.$nextTick(() => {
          this.loading = false
        })
      })
    },
    computed: {

    },
    methods: {
      async loadRoles() {
        let res = await Role.list()
        let roles = []
        for (let i = 0; i < res.data.length; i++) {
          let role = res.data[i]
          roles.push({
            key: role.id,
            label: role.name
          })
        }
        this.data = roles
      },
      async loadUserRoles() {
        let username = this.$route.params.username
        let res = await Role.userRole(username)
        let roles = []
        for (let i = 0; i < res.data.length; i++) {
          let role = res.data[i]
          roles.push(role.id)
        }
        this.choosed = roles
      },
      async save() {
        showSaveResponse(this, () => this.saveUserRole(), this.$router.back())
      },
      async saveUserRole() {
        let username = this.$route.params.username
        return Role.saveUserRole(username, this.choosed)
      }
    },
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>
